package fun.easycode.webterminal.common.jsch;

import cn.hutool.extra.ssh.Sftp;
import com.jcraft.jsch.SftpException;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class JschPasswdQuery {

    private final List<String[]> lines = new ArrayList<>();

    public JschPasswdQuery(Sftp sftp) throws SftpException, IOException {

        Reader iReader = new InputStreamReader(sftp.getClient().get("/etc/passwd"), StandardCharsets.UTF_8);

        try (BufferedReader reader = new BufferedReader(iReader)) {
            for (;;) {
                String line = reader.readLine();
                if (line == null)
                    break;
                lines.add(line.split(":"));
            }
        }

    }

    public String getUserName(int uid) {
        for (String[] line : lines) {
            if (line[2].equals(String.valueOf(uid))) {
                return line[0];
            }
        }
        return "";
    }
}
